import router from '../router'
import store from '../store'
import { PID, savePid, setLastPath } from '../cookie'
import Wx from '../wx'
import { LEVELS } from '../const'
// 白名单
const whiteList = ['/login', '/ban', '/code', '/register', '/lottery']
// 游客能且只能访问的
// const cusList = ['/order/img']
const cusList = []
// 终端代表才可以
// const busList = ['/plan']
const busList = []
// 管理员才可以
const manList = ['/score']

// const KeepRouter = [['/todo/type', '/todo/head'], ['/todo/type', '/todo/visit'], ['/todo/type', '/todo/send'], ['/todo/type', '/todo/link'], ['/todo/type', '/todo/act'], ['/todo/type', '/todo/hunt'],
//   ['/todo/type', '/score/head'], ['/todo/type', '/score/visit'], ['/todo/type', '/score/send'], ['/todo/type', '/score/link'], ['/todo/type', '/score/act'], ['/todo/type', '/score/hunt']
// ]
router.beforeEach((to, from, next) => {
  const toPath = to.path
  saveParams(to)
  // 微信地址要获取签名用的
  Wx.setPath(to.fullPath)
  const token = store.state.user.token

  if (whiteList.indexOf(toPath) > -1) { // 白名单直接放
    next()
  } else { // 非白名单 需要登录
    if (!token) { // 没有登录
      // 存储上一次的页面
      setLastPath(to.fullPath)
      next('/login')
      return
    }
    // 登录了
    // 游客页面 非游客跟药店去了
    // eslint-disable-next-line eqeqeq
    if (cusList.indexOf(toPath) > -1 && store.state.user.levelId != LEVELS.CUSTOM && store.state.user.levelId != LEVELS.SHOP) {
      next('/ban')
      return
    }
    // 非游客页面 游客去了
    if (cusList.indexOf(toPath) < 0 && store.state.user.levelId === LEVELS.CUSTOM) {
      // next('/ban')
      next('/order/img')
      return
    }
    // 如果是非终端代表去了终端代表页面
    if (busList.indexOf(toPath) > -1 && store.state.user.levelId !== LEVELS.BUS) {
      next('/ban')
      return
    }
    // 如果是非管理去了终端代表页面
    if (manList.indexOf(toPath) > -1 && store.state.user.levelId < LEVELS.MANAGER) {
      next('/ban')
      return
    }
    // if (from.path == '/todo/type' && to.path == '/plan/week') {
    //   from.meta.keepAlive = false
    // } else {
    //   to.meta.keepAlive = true
    // }
    // for (const k in KeepRouter) {
    //   if (from.path == KeepRouter[k][0] && to.path == KeepRouter[k][1]) {
    //     from.meta.keepAlive = true
    //     console.log('11')
    //     break
    //   } else {
    //     console.log('22')
    //     from.meta.keepAlive = false
    //   }
    // }
    // 放行
    next()
  }
})

// 通过Cookie存储一些需要保存的信息到本地
const saveParams = function (to) {
  console.log(JSON.stringify(to.query) + '==>')
  const pid = to.query[PID]
  if (pid) {
    savePid(pid)
  }
}
